﻿using System;
using System.Collections.Generic;
using IQIGame.Onigao.GamePlay;
using LFloatMath.Math;

namespace IQIGame.Onigao.Logic
{
    public class FormulaFunction_MaxAttribute : FormulaFunction
    {
        public override EFormulaFunctionType funcType => EFormulaFunctionType.bMaxAttribute;

        public override void Calculate(Stack<IFormulaOperand> rCalopd, IFormulaObject rSelf, IFormulaObject rTarget, Formula rFromFormula)
        {
            IFormulaOperand opd1 = rCalopd.Pop();
            IFormulaOperand opd2 = rCalopd.Pop(); // 队伍ID -1表示全体
            if (opd1.TryGet<LFloat>(out var op1, rSelf, rTarget, rFromFormula) && opd2.TryGet<LFloat>(out var op2, rSelf, rTarget, rFromFormula))
            {
                var nResult = LFloat.zero;
                var nOp1 = op1.ToInt();
                var nOp2 = op2.ToInt();
                var rTargetUnits = rSelf.GetUnits(nOp2);

                if (rTargetUnits != null)
                {
                    foreach (var rUnit in rTargetUnits)
                    {
                        var rAttrComp = rUnit.GetAttr();
                        var rValue = rAttrComp.Get((EAttributeType)nOp1);
                        if (rValue > nResult)
                        {
                            nResult = rValue;
                        }
                    }
                }
                
                IFormulaOperand result = FormulaHelper.FetchOperand(EFormulaOperandType.Num);
                result.Set(nResult);
                rCalopd.Push(result);
            }
            else
            {
                throw new Exception($"{funcType} func need two number");
            }

            opd1.TryFree();
            opd2.TryFree();
        }
    }
}